<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Vote;
use Illuminate\Http\Request;
use File;

class VotesController extends Controller
{
  public function __construct()
  {
    $this->middleware('admin');
  }

  private function setLock($id, $lock)
  {
    $vote = Vote::findOrFail($id);
    $vote->is_lock = $lock;
    $vote->save();
  }

  public function index($type = 0)
  {
    $data['title'] = '投票管理';
    $data['votes'] = Vote::where('is_lock', '=', $type)->paginate(12);

    return view('admin.votes.index', $data);
  }

  public function edit($id)
  {
    $data['title'] = '投票管理';
    $vote = Vote::findOrFail($id);
    $data['vote'] = $vote;

    return view('admin.votes.edit', $data);
  }

  public function update($id, Request $request)
  {
    $vote = Vote::findorFail($id);
    $vote->fill($request->all());

    if ($request->hasFile('img')) {
      $imgName = date('Y-m-d') . '_' . uniqid() . '.jpg';
      $img = $request->file('img')->move(public_path() . '/uploads/', $imgName);
      File::delete(public_path(). '/'. $vote->img_src);
      $vote->img_src = 'uploads/' . $img->getFilename();
    }
    $vote->save();

    return redirect()->to('admin/votes');
  }

  public function destroy($id)
  {
    Vote::destroy($id);

    return redirect()->back();
  }

  public function postPassed($id)
  {
    $this->setLock($id, 1);

    return redirect()->back();
  }

  public function postLocked($id)
  {
    $this->setLock($id, 2);

    return redirect()->back();
  }
}
